package com.bird.framework.security.service;

import com.bird.common.constant.Constants;
import com.bird.common.utils.MessageUtil;
import com.bird.framework.security.token.WeiXinMaAuthenticationToken;
import com.bird.framework.thread.AsyncManager;
import com.bird.framework.thread.factory.AsyncFactory;
import com.bird.system.domain.bo.LoginUser;
import com.bird.system.domain.bo.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 微信登录校验方法
 *
 * @author bird
 */
@Component
public class WxLoginService {

	private static final Logger LOGGER = LoggerFactory.getLogger(WxLoginService.class);

	@Autowired
	private TokenService tokenService;

	@Resource
	private AuthenticationManager authenticationManager;

	/**
	 * 登录验证
	 *
	 * @param code 微信令牌
	 * @return 结果
	 */
	public String login(String code) {
		// 用户验证
		WeiXinMaAuthenticationToken authentication = (WeiXinMaAuthenticationToken) authenticationManager.authenticate(new WeiXinMaAuthenticationToken(code));
		LoginUser loginUser = (LoginUser) authentication.getDetails();
		Subject member = loginUser.getUser(Subject.class);
		AsyncManager.me().execute(AsyncFactory.recordLogininfor(member.getId().toString(), loginUser.getLoginType(), Constants.System.LOGIN_SUCCESS, MessageUtil.message("user.login.success")));
		// 生成token
		return tokenService.createToken(loginUser);
	}
}
